package cn.wjzhang.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import cn.wjzhang.entity.NavCategoryEntity;
import cn.wjzhang.mapper.NavCategoryMapper;
import cn.wjzhang.service.NavCategoryService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 导航分类
 *
 * @author wj
 * @date 2023-09-27 17:21:12
 */
@Service
public class NavCategoryServiceImpl extends ServiceImpl<NavCategoryMapper, NavCategoryEntity> implements NavCategoryService {
	@Override
	public List<Tree<Long>> treeCategory(Long parentId, String categoryName, String type) {
		Long parent = parentId == null ? -1 : parentId;

		List<TreeNode<Long>> collect = baseMapper
				.selectList(Wrappers.<NavCategoryEntity>lambdaQuery()
						.like(StrUtil.isNotBlank(categoryName), NavCategoryEntity::getCategoryName, categoryName)
						.eq(NavCategoryEntity::getDelFlag, "0")
						.orderByAsc(NavCategoryEntity::getSort))
				.stream()
				.map(getNodeFunction())
				.collect(Collectors.toList());

		// 模糊查询 不组装树结构 直接返回 表格方便编辑
		if (StrUtil.isNotBlank(categoryName)) {
			return collect.stream().map(node -> {
				Tree<Long> tree = new Tree<>();
				tree.putAll(node.getExtra());
				BeanUtils.copyProperties(node, tree);
				return tree;
			}).collect(Collectors.toList());
		}

		return TreeUtil.build(collect, parent);
	}

	private Function<NavCategoryEntity, TreeNode<Long>> getNodeFunction() {
		return category -> {
			TreeNode<Long> node = new TreeNode<>();
			node.setId(category.getId());
			node.setName(category.getCategoryName());
			node.setParentId(category.getParentId());
			node.setWeight(category.getSort());
			// 扩展属性
			Map<String, Object> extra = new HashMap<>();
			extra.put("sort", category.getSort());

			// 适配 vue3
			Map<String, Object> meta = new HashMap<>();
			meta.put("title", category.getCategoryName());
//			meta.put("isAffix", false);
			meta.put("icon", category.getIcon());
			// 增加英文
			meta.put("enName", category.getCategoryName());

			extra.put("meta", meta);
			node.setExtra(extra);
			return node;
		};
	}
}